﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using System.Text.RegularExpressions;
using ZyGames.Framework.Net;
using ZyGames.Framework.Common.Serialization;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 获得自己被邀请的信息
	/// </summary>
	public class Action30057 : BaseAction
	{
		private int tableId;
		private int userId;
		private string beInvitedInfoStr;
		private bool result = true;
		private string log = "";
		public Action30057(HttpGet actionGetter)
			: base((short)ActionType.DZGetBeInvitedInfo, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableId", ref tableId) &&  //TableId是0的话说明在消息列表里面请求的所有列表，则返回所有的，如果不是0则只返回当前那一桌的
				httpGet.GetInt("UserId", ref userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			if (tableId != 0)
			{
				var _currentTable = GameRoom.Current.GetTableData(tableId);
				if (_currentTable == null)
				{
					Tool.WriteWarmingLine("消息30057获得房间不存在");
					log = "房间不存在";
					result = false;
					return true;
				}
			}

			var user = GameTable.Current.GetUser(userId);
			if (user == null)
			{
				Tool.WriteWarmingLine("消息30057玩家不存在");
				log = "信息有误";
				result = false;
				return true;
			}

			var invitedInfo = GameTable.Current.GetAllInvitesByBeInvitedUserId(userId);
			Dictionary<int, SimpleUserData> invitedInfoList = new Dictionary<int, SimpleUserData>();
			if(invitedInfo.Count > 0)
			{
				if (tableId != 0)
				{
					int inviteUserId;
					if (invitedInfo.TryGetValue(tableId, out inviteUserId))
					{
						invitedInfoList = new Dictionary<int, SimpleUserData>();
						var tempUser = GameTable.Current.GetUser(inviteUserId);
						if(tempUser != null)
						{
							invitedInfoList.Add(tableId, new SimpleUserData() { HeadIcon = tempUser.HeadIcon, NickName = tempUser.NickName, UserId = tempUser.UserId });
						}
					}
				}
				else
				{
					foreach(var record in invitedInfo)
					{
						var tempUser = GameTable.Current.GetUser(record.Value);
						if(tempUser != null)
						{
							invitedInfoList.Add(record.Key, new SimpleUserData() { HeadIcon = tempUser.HeadIcon, NickName = tempUser.NickName, UserId = tempUser.UserId });
						}
					}
				}
			}
			beInvitedInfoStr = Convert.ToBase64String(ProtoBufUtils.Serialize(invitedInfoList));
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.result);
			this.PushIntoStack(this.log);
			this.PushIntoStack(this.beInvitedInfoStr);
		}
	}
}
